<template>
  <div class="common-table">
    <div class="table-item">
      <formItem title="名称">
        <template v-slot:rightText>
          <span>{{ formObj.title }}</span>
        </template>
      </formItem>
      <formItem title="位置">
        <template v-slot:rightText>
          <span>{{ formObj.location }}</span>
        </template>
      </formItem>
      <formItem title="面积">
        <template v-slot:rightText>
          <span>{{ formObj.area }}</span>
        </template>
      </formItem>
    </div>
    <div class="table-item">
      <formItem title="区镇">
        <template v-slot:rightText>
          <span>{{ formObj.town }}</span>
        </template>
      </formItem>
      <formItem title="类型">
        <template v-slot:rightText>
          <span>{{ formObj.type }}</span>
        </template>
      </formItem>
      <formItem title="用途">
        <template v-slot:rightText>
          <span>{{ formObj.class }}</span>
        </template>
      </formItem>
    </div>
    <div class="table-item" v-for="(item,index) in fileObj" :key="index" :item="item">
      <formItem v-bind:title="index>0 ? '材料'+index : '汇总表' ">
        <template v-slot:rightFull>
          <div class="table-item-step-five">
            <div class="table-item-five-input">
              <el-input v-model="item.name" placeholder="请输入名称" type="text"/>
            </div>
            <div class="table-item-step-five-button">
              <el-button type="primary" @click="download(item.url,item.name,item.name)">下载</el-button>
              <el-button type="primary" @click="preview(item.url,item.name,item.value)">浏览</el-button>
            </div>
            <el-upload
                method="post"
                :http-request="passUrl"
                style="width: 10%"
                :show-file-list="false"
            >
              <el-button type="primary" style="margin-left:12px" @click="deleteWord(item.url,item.name,item.value)">重新上传</el-button>
            </el-upload>
          </div>
        </template>
      </formItem>
    </div>
    <el-button class="add-question" @click="add">添加按钮</el-button>
  </div>
</template>
<script lang="ts">
import {reactive, defineComponent, getCurrentInstance, onMounted, watch, ref} from 'vue'
import formItem from "@/components/commonFomItem/index.vue";
import {ElMessageBox, ElNotification} from "element-plus";
import {useRouter} from "vue-router";

export default defineComponent({
  components: {formItem},
  props: ['confirmState', 'index', 'PassState','userName'],
  emits: ['receiveStateId'],
  setup(props, context) {
    const userType = localStorage.getItem("userType")
    const loginName = localStorage.getItem("loginName");
    //获取当前时间
    const getCurrentTime = () => {
      let date = new Date();
      //年
      let year = date.getFullYear().toString();
      //月份是从0月开始获取的，所以要+1;
      let month = ''
      if ((date.getMonth() + 1) < 10) {
        month = '0' + (date.getMonth() + 1).toString()
      } else {
        month = (date.getMonth() + 1).toString()
      }
      //日
      let day = date.getDate().toString();
      //时
      let hour = date.getHours().toString();

      return year + '年' + month + '月' + day + '日' + hour +'时'
    }
    const formObj = reactive({
      class: '',
      title: '',
      town: '',
      location: '',
      area: '',
      type: ''
    })
    const fileObj = reactive([
      {
        value: 1,
        url: '',
        name: ''
      }

    ])
    const {appContext} = getCurrentInstance();
    const router = useRouter();
    const itemId = ref(0)
    //读取数据库数据
    const readData = (url: string, name: string, index: number) => {
      if ((url != "" && url != null) && (name != "" && name != null)) {
        let Object = {
          value: index,
          url: url,
          name: name
        }
        fileObj.push(Object)
        itemId.value++
      }

    }
    //浏览内容
    const preview = (url,name,id) => {
      if(url === ' ' || name ===''){
        ElNotification({
          title: '预览文件',
          message: "文件地址有问题，请检查文件",
          type: 'warning',
          position: 'top-left',
          offset: 300,
        })
      }
      else{
        if(name.includes("pdf")){
          window.open(`api/explore/getFile?path=${url}&name=${name}`, '_blank')
        }
        else{
          // resolve新窗口打开
          const newPage = router.resolve({
            path: '/preview',  // 跳转的页面路由
            query: { // 要传的参数
              url: url+'//'+name,
              index: props.index
            }
          })
          window.open(newPage.href, '_blank') // 打开新的窗口(跳转路径，跳转类型)
        }

      }

    }
    //删除文件的操作
    const deleteWord = (url,name,index) => {
      itemId.value = index-1
      if(url!=''){
        appContext.config.globalProperties.axios({
          url:`api/delete/word`,
          method: 'post',
          data:formObj,
          transformRequest: [function () {
            let oMyForm = new FormData();
            oMyForm.append("path", url);
            oMyForm.append("name", name);
            return oMyForm;
          }]
        }).then(() => {
          ElNotification({
            title: '删除文件',
            message: "删除成功",
            type: 'success',
            position: 'top-left',
            offset: 300,
          })
        })
      }
    }

    //传送url
    const passUrl = (Option) => {
      appContext.config.globalProperties.axios({
        url: `api/upload/fileStore`,
        method: 'post',
        transformRequest: [function () {
          let oMyForm = new FormData();
          oMyForm.append("file", Option.file);
          oMyForm.append("landId", props.index);
          oMyForm.append("infoDate", getCurrentTime());
          oMyForm.append("userType",userType);
          oMyForm.append("content", loginName +"于"+getCurrentTime()+"，在"+formObj.title+"地块收储协议阶段上传了");
          return oMyForm;
        }]
      }).then((response) => {
        fileObj[itemId.value].name = Option.file.name
        fileObj[itemId.value].url = response.data
        ElNotification({
          title: '上传文件',
          message: "上传成功",
          type: 'success',
          position: 'top-left',
          offset: 300,
        })
      })
    }

    //下载文件
    const download = (url, name) => {
      appContext.config.globalProperties.axios({
        url: `api/downloadWord`,
        method: 'post',
        data: formObj,
        transformRequest: [function () {
          let oMyForm = new FormData();
          oMyForm.append("landId", props.index);
          oMyForm.append("path", url + '//' + name);
          return oMyForm;
        }],
        responseType: "blob",
      }).then((response) => {
        let blob = new Blob([response.data], {type: "application/msword;"});
        let url = window.URL.createObjectURL(blob); // 创建一个临时的url指向blob对象
        let a = document.createElement("a");
        a.href = url;
        a.download = name;
        a.click();
        // 释放这个临时的对象url
        window.URL.revokeObjectURL(url);
      }).catch(()=>{
        ElNotification({
          title: '下载文件',
          message: "文件未上传，请上传文件",
          type:'warning',
          position: 'top-left',
          offset: 300,
        })
      })
    }

    //添加按钮
    const add = () => {
      if (fileObj.length < 6) {
        fileObj.push({
          value: fileObj.length + 1,
          url: '',
          name: ''
        })
      } else {
        ElNotification({
          title: '添加文件资料',
          message: "材料数量已达上限",
          type: 'warning',
          position: 'top-left',
          offset: 300,
        })
      }
    }

    //确定键
    watch(() => props.confirmState, () => {
      pushData()
    })
    const pushData = () => {
      // console.log(fileObj)
      for (let i = 0; i < fileObj.length; i++) {
        appContext.config.globalProperties.axios({
          url: `api/update/fileStore/${fileObj[i].value}`,
          method: 'post',
          transformRequest: [function () {
            let oMyForm = new FormData();
            oMyForm.append("landId", props.index);
            oMyForm.append("fileUrl1", fileObj[i].url);
            oMyForm.append("fileName1", fileObj[i].name);
            return oMyForm;
          }]
        })
      }
        ElNotification({
          title: '修改数据',
          message: "修改成功",
          type: 'success',
          position: 'top-left',
          offset: 300,
        })
    }
    //通过键
    watch(() => props.PassState, () => {
      passData()
    })
    const passData = () => {
      for (let i = 0; i < fileObj.length; i++) {
        appContext.config.globalProperties.axios({
          url: `api/pass/fileStore/1/${fileObj[i].value}`,
          method: 'post',
          transformRequest: [function () {
            let oMyForm = new FormData();
            oMyForm.append("landId", props.index);
            oMyForm.append("fileUrl1", fileObj[i].url);
            oMyForm.append("fileName1", fileObj[i].name);
            return oMyForm;
          }]
        })
      }
    }

    //初始化数据
    onMounted(() => {
      appContext.config.globalProperties.axios.post(`api/landSearch/${props.index}`).then((response) => {
        response.data.forEach(item => {
          formObj.class = item.landType
          formObj.title = item.bz
          formObj.town = item.town
          formObj.location = item.landLoc
          formObj.area = item.landArea
          formObj.type = item.type
        })
      })
      setTimeout(()=>{
        appContext.config.globalProperties.axios.post(`api/search/fileStore/${props.index}`).then((response) => {
          response.data.forEach(item => {
            fileObj[0].url = item.fileUrl1
            fileObj[0].name = item.fileName1
            readData(item.fileUrl2, item.fileName2, 2)
            readData(item.fileUrl3, item.fileName3, 3)
            readData(item.fileUrl4, item.fileName4, 4)
            readData(item.fileUrl5, item.fileName5, 5)
            readData(item.fileUrl6, item.fileName6, 6)
          })
        },300)
      })

    })
    return {
      formObj,
      fileObj,
      readData,
      preview,
      deleteWord,
      passUrl,
      download,
      add,
      getCurrentTime
    }
  }
})
</script>


<style scoped lang="scss">
.common-table {
  .add-question {
    width: 130px;
    height: 28px;
    background: rgba(255, 255, 255, 0.002);
    border: 1px solid rgba(245, 248, 255, 0.25);
    border-radius: 4px;
    color: rgba(240, 245, 255, 0.95);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 16px;
    cursor: pointer;
  }

  .table-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;

    .table-full-text {
      display: flex;
      width: 100%;
      align-items: center;

      .left {
        color: rgba(240, 245, 255, 0.95);
        padding-right: 10px;
        width: 61px;
      }

      .right {
        flex: 1;

        .red-line {
          display: flex;
          align-items: center;

          .red-line-text {
            padding-right: 12px;
          }
        }
      }
    }
  }

  .empty-form-item {
    width: 280px;
  }

  .tips-text {
    margin-left: 62px;
    margin-top: -16px;
  }

  .table-item-input-btn {
    position: relative;

    .float-btn {
      position: absolute;
      right: 2px;
      top: 0;
    }
  }
}

.table-item-step-five {
  display: flex;
  align-items: center;

  .table-item-five-input {
    width: 512px;
    padding-left: 16px;
  }

  .table-item-step-five-button {
    padding-left: 18px;
  }
}
</style>
